<?php 

class My_Acl extends Zend_Acl {

	public function __construct($rq){
		
		$this->acl_check($rq);
		
		$this->make_roles();
		$this->make_assets();
		$this->make_rules();
	}
	
	private function acl_check($rq){
		$state = Utils::getSetup('acl_state');

		if(!$state || $state == '0'){
			$conn = Zend_Db_Table::getDefaultAdapter()->getConnection();
			$exe = function ($files) use ($conn,$rq){
				foreach($files as $file){
					$conn->exec(file_get_contents(dirname(__FILE__) . '/SQL/'.$file.'.sql'));
					Utils::logHard(array($file=>'OK','RQ'=>json_encode($rq->getParams())));
				}
			};
			$exe(array(
				'truncate_acl',
				'setup',
				'acl_roles',
				'acl_structure',
				'acl_actions',
				'acl_rules',
				'acl_modules',
				'acl_module_rules',
				'revive_users'
			));		
			Utils::setSetup('acl_state',1);
		}
		
	}
	
	private function make_roles(){
		
		$t = new AclRole();
		$r = $t->fetchAll(null, 'role_priority ASC');
		
		if($r->count()>0){
			while($o = $r->current()){
				$drows = $o->findDependentRowset('AclStructure');
				$parents = $drows->count()>0?array():null;				
				
				while($do = $drows->current()){
					$darr = $do->toArray();
					array_push($parents,$darr['parent_id']);
					$drows->next();
				}
				$oarr = $o->toArray();
				$this->addRole(new Zend_Acl_Role($oarr["role_id"]),$parents);
				$r->next();
			}
		} else Utils::log($r);		
	}
	
	private function make_assets(){
		
		$act = new AclAction();
		$res = $act->fetchAll();
		
		if($res->count()>0){
			while($r = $res->current()){
				$this->addResource(new Zend_Acl_Resource($r->action_name));
				$res->next();
			}
		}
		
	}
	
	private function make_rules(){
		
		$rules = new AclRule();
		$acts = new AclAction();
				
		$db = Zend_Db_Table::getDefaultAdapter();
		$q = $db->query($db->select()
			->from(array('r'=>$rules->info('name')),array('role_id'))
			->join(array('a'=>$acts->info('name')), 'a.action_id = r.action_id',array('action_name'))
		);
		
		if($q->rowCount()>0){
			while($r = $q->fetch()){
				$this->allow($r["role_id"], $r["action_name"]);
			}
		}
		
	}
	
}

?>